#!/bin/env python
# -*- coding: utf-8 -*-

__all__ = [u'PathBook']

from _pylot.core.datum import Identity
from _pylot.core.book import Book
from _pylot.core.path import Path
from _pylot.core.system import ENCODING

class PathBook (Book) :
  u"""
  Special Book designed for Path

  Takes two extra parameters
    - expanduser : if True [default] convert ~ to /home/user
    - abspath : if True [default] always return absolute paths

  Example :

  >>> from pylot.core import Datum
  >>> b = PathBook(Datum(u'abs', Path, u'/tmp/dir'))
  >>> b[u'abs']
  Datum(u'abs', Path, Path(u'/tmp/dir'), None, [Path(u'/tmp/dir')], None, None, None)

  >>> print b.nature
  <class '_pylot.core.path.Path'>
  >>> b(u'abs')
  Path(u'/tmp/dir')
  
  >>> import os
  >>> b[u'home'] = u'~/test'
  >>> b(u'home') == os.path.expanduser(u'~/test')
  True
  
  >>> b[u'INT']=12
  Traceback (most recent call last):
     ...
  TypeError: E006 - Path, unicode expected, got int
  >>> u'INT' in b
  False
  
  >>> b.identity
  Identity(name=u'AnonymousPathBook', nature=Path, tooltip=None, group=None, alias=u'Anonymous pathBook')
  """
  def __init__ (self, *args, **kargs):

    try : kargs[u'identity']
    except KeyError :
      kargs[u'identity'] = Identity(u"AnonymousPathBook", nature=Path,
                                   alias=u"Anonymous pathBook")
    else :
      kargs[u'identity'].nature = Path

    # TODO: Python3: remove lines from here ...
    new_dict = {}
    for key, value in kargs.items() :
      new_dict[key.encode(ENCODING)] = value
    # ... to here

    super(PathBook, self).__init__(*args, **new_dict)

    self.expanduser = True
    self.abspath = True

  def convert(self, val, nat):
    return self.nature(val).expanduser()

  def __call__ (self, pathid, *args) :
    u"""
    Returns absolute path

    :param pathid: path identifier (:attr:`Datum.name<pylot.core.Datum.name>`)
    :type pathid: str

    :return: absolute path (:class:`~pylot.core.Path`)
    """
    path = self[pathid].value
    if path is None : return None
    else :

      if args :
        path = Path(path, *args)

      if self.expanduser : path = path.expanduser()
      if self.abspath : path = path.abspath()

      return path

if __name__ == u'__main__' :

  import doctest
  doctest.testmod()

